<?php

class Kpl_Action_Helper_ConnManager extends Zend_Controller_Action_Helper_Abstract {

	protected $_userHelper;

	public function getConnection()
	{		

		
		if (Zend_Registry::isRegistered('db') && is_array(Zend_Registry::get('db'))) {
			$db = Zend_Registry::get('db');
			if ($db['name'] == $this->getConnName()) return $db['conn'];
		}

		$db['name'] = $this->getConnName();
		$db['conn'] = $this->_getConnection();
		//echo $this->getConnName();
		Zend_Registry::set('db',$db);

		return $db['conn'];

	}


	public function getConnName() {
		if ($this->_getUserHelper()->getInfo()) {
			return $this->_getUserHelper()->getInfo()->login;
		} else return 'default';
	}

	private function _getUserHelper() {
		if (!$this->_userHelper) {
			include_once('User.php');
			$this->_userHelper = new Kpl_Action_Helper_User;
		}

		return $this->_userHelper;
	}


	private function _getConnection()
	{
	

		$config = Util::getConfig(true);
	
		if ($this->_getUserHelper()->getInfo()) {
			$login = $this->_getUserHelper()->getInfo()->login;
			$pswd =  $this->_getUserHelper()->getInfo()->pswd;
			$group = $this->_getUserHelper()->getCurrentGroup();
		} else {
			if ($config->auth->type == 'ldap' && !Zend_Registry::get('context')=='test') throw new Exception ("If auth type set to LDAP, you should be already authorized
				to get DB connection");
		}
	
		if ($db = $config->get('db')) {
				if ($params = $db->get('params')) {
					if ($options = $params->get('options',' ')) {
						$options = explode(' ',$options);
						if ($login) $options[] = 'effective_user="'.$login.'"';
						if ($group) $options[] = 'group="'.$group.'"';
	
						$options = trim(implode(' ',$options));
						$config->db->params->options = $options;
					}
				}
		}

			
		$adapter = (string)$config->db->adapter;
		$params = $config->db->params->toArray();
		
		
		$result = Zend_Db::factory($adapter, $params);

		return $result;
	}
}
